<?php
/**
 * 首页Service
 * Date: 2025/09/17
 */

namespace App\Services\Admin;

use App\Models\ViewModel;
use App\Services\BaseService;

class HomeService extends BaseService
{
    /**
     * 浏览量概述
     * @date 2025/09/17
     * @return \Illuminate\Http\JsonResponse
     */
    public function overview()
    {
        // 今天和昨天的统计概述
        $todayCount = $this->getView(date('Y-m-d'));
        $yesterdayCount = $this->getView(date('Y-m-d', strtotime('-1 day')));

        // 今天较昨天的浏览量（pv）比例计算
        $todayViewCount = $todayCount['view_count'] ?? 0;
        $yesterdayViewCount = $yesterdayCount['view_count'] ?? 0;
        $dayViewCountRatio = empty($yesterdayViewCount) ? 0 : round(($todayViewCount - $yesterdayViewCount) / $yesterdayViewCount * 100, 2);

        // 今天较昨天的用户（uv）比例计算
        $todayIpCount = $todayCount['ip_count'] ?? 0;
        $yesterdayIpCount = $yesterdayCount['ip_count'] ?? 0;
        $dayIpCountRatio = empty($yesterdayIpCount) ? 0 : round(($todayIpCount - $yesterdayIpCount) / $yesterdayIpCount * 100, 2);

        // 本月和上月的统计查询
        $thisMonthCount = $this->getView([date('Y-m-01'), date('Y-m-t')]);
        $lastMontyCount = $this->getView([date('Y-m-01', strtotime('first day of last month')), date('Y-m-t', strtotime('last day of last month'))]);

        // 本月较上月的浏览量（pv）比例计算
        $thisMonthViewCount = $thisMonthCount['view_count'] ?? 0;
        $lastMontyViewCount = $lastMontyCount['view_count'] ?? 0;
        $monthViewCountRatio = empty($lastMontyViewCount) ? 0 : round(($thisMonthViewCount - $lastMontyViewCount) / $lastMontyViewCount * 100, 2);

        // 本月较上月的用户（uv）比例计算
        $thisMonthIpCount = $thisMonthCount['ip_count'] ?? 0;
        $lastMontyIpCount = $lastMontyCount['ip_count'] ?? 0;
        $monthIpCountRatio = empty($lastMontyIpCount) ? 0 : round(($thisMonthIpCount - $lastMontyIpCount) / $lastMontyIpCount * 100, 2);

        // 返回统计
        return $this->success([
            'day_view_count' => [
                'num' => $todayViewCount,
                'ratio' => abs($dayViewCountRatio) . '%',
                'sign' => $dayViewCountRatio >= 0 ? '+' : '-'
            ],
            'day_ip_count' => [
                'num' => $todayIpCount,
                'ratio' => abs($dayIpCountRatio) . '%',
                'sign' => $dayIpCountRatio >= 0 ? '+' : '-'
            ],
            'month_view_count' => [
                'num' => $thisMonthViewCount,
                'ratio' => abs($monthViewCountRatio) . '%',
                'sign' => $monthViewCountRatio >= 0 ? '+' : '-'
            ],
            'month_ip_count' => [
                'num' => $thisMonthIpCount,
                'ratio' => abs($monthIpCountRatio) . '%',
                'sign' => $monthIpCountRatio >= 0 ? '+' : '-'
            ]
        ]);
    }

    /**
     * 根据时间查询浏览数据
     * @date 2025/09/17
     * @param string|array $time 时间
     * @return array
     */
    public function getView($time)
    {
        $data = ViewModel::query()
            ->selectRaw('sum(pv) as view_count, count(distinct ip) AS ip_count')
            ->where('type', ViewModel::TYPE_HOME)
            ->when(!empty($time), function ($query) use ($time) {
                if (is_array($time)) {
                    $query->where('date', '>=', $time[0])->where('date', '<=', $time[1]);
                } else {
                    $query->where('date', $time);
                }
            })
            ->first();
        return !empty($data) ? $data->toArray() : [];
    }


    /**
     * 浏览量统计图
     * @date 2025/09/17
     * @param int $type 查询类型（1：访问次数，2：访客数）
     * @param string $startTime 开始时间，例如：2025-09-15
     * @param string $endTime 结束时间，例如：2025-09-17
     * @return \Illuminate\Http\JsonResponse
     */
    public function chart($type, $startTime, $endTime)
    {
        $dayCountList = ViewModel::query()
            ->when($type == 1, function ($query) {
                $query->selectRaw('date, sum(pv) as count');
            }, function ($query) {
                $query->selectRaw('date, count(distinct ip) AS count');
            })
            ->where('type', ViewModel::TYPE_HOME)
            ->where('date', '>=', $startTime)
            ->where('date', '<=', $endTime)
            ->groupBy('date')
            ->pluck('count', 'date')
            ->toArray();

        // 按照时间处理数据
        $analysisList = [];
        $curDate = date('Y-m-d', strtotime($startTime));
        while (strtotime($curDate) <= strtotime($endTime)) {
            $analysisList[] = [
                'date' => $curDate,
                'count' => $dayCountList[$curDate] ?? 0
            ];
            $curDate = date('Y-m-d', strtotime($curDate . ' +1 day'));
        }
        return $this->success($analysisList);
    }
}
